package com.coldchain.cys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coldchain.common.exception.base.BusinessException;
import com.coldchain.common.msg.BaseResponse;
import com.coldchain.common.msg.ObjectRestResponse;
import com.coldchain.common.util.FunctionUtils;
import com.coldchain.cys.constant.Constant;
import com.coldchain.cys.context.CarDriverContext;
import com.coldchain.cys.entity.CysAccount;
import com.coldchain.cys.entity.CysAccountDetail;
import com.coldchain.cys.mapper.CysAccountMapper;
import com.coldchain.cys.service.ICarDriverService;
import com.coldchain.cys.service.ICarService;
import com.coldchain.cys.service.ICysAccountDetailService;
import com.coldchain.cys.service.ICysAccountService;
import com.fangliai.core.context.BaseContextHandler;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tianpeng
 * @since 2018-09-05
 */
@Service
public class CysAccountServiceImpl extends ServiceImpl<CysAccountMapper, CysAccount> implements ICysAccountService {
	
//	@Autowired
//	private BizDispatchingOrderFeign orderFeign ;
	
	@Autowired
	private ICarService carService ;
	
	@Autowired
	private ICarDriverService carDriverService ;
	
	@Autowired
	private ICysAccountDetailService cysAccountDetailService ;
	
	private Logger logger = Logger.getLogger(CysAccountServiceImpl.class) ;
	
	@Override
	public CysAccount getByCid(String cid) {
		QueryWrapper<CysAccount> ew = new QueryWrapper<CysAccount>();
		ew.eq(true,"cid", cid) ;
		CysAccount cysAccount = super.getOne(ew);
		return cysAccount ;
	}

	@Override
	public CysAccount getCurrentByCid() {
		return getByCid(BaseContextHandler.getCysID()) ;
	}

	@Transactional
	@Override
	public BaseResponse doHandleAccount(String orderId, String signature, String key) {
		Long driverid = CarDriverContext.getCarDriverId();
		if(StrUtil.isBlank(orderId)) {
			return getErrorMessage("签名不合法") ;
		}
		if(StrUtil.isBlank(signature)) {
			return getErrorMessage("签名不合法") ;
		}
		if(StrUtil.isBlank(key)) {
			return getErrorMessage("签名不合法") ;
		}
//		OrderSearch orderSearch = new OrderSearch();
//		orderSearch.setOrderid(orderId);
//		ObjectRestResponse<PageResponse<Order>> orderRestResult = orderFeign.sysOrder(orderSearch);
//		if(orderRestResult.getStatus() != 200) {
//			return getErrorMessage(orderRestResult.getMessage()) ;
//		}
		
//		PageResponse<Order> data = orderRestResult.getData();
//		if(data == null || data.getRecords() == null || data.getRecords().size() != 1) {
//			return getErrorMessage("数据异常") ;
//		}
//		Order order = data.getRecords().get(0); //订单
//		if(order.getStatus() != 1) {
//			return getErrorMessage("订单还未支付") ;
//		}
//		if(order.getSettlementCode() != 0) {
//			return getErrorMessage("该订单已结算了") ;
//		}
//		ObjectRestResponse<BizDispatchingOrdercao> bizRestResult = orderFeign.getBizInfoByOrder(order.getOrderId());
//		if(bizRestResult.getStatus() != 200){
//			return getErrorMessage(bizRestResult.getMessage()) ;
//		}
//		BizDispatchingOrdercao biz = bizRestResult.getData();
//		if(biz == null) {
//			return getErrorMessage("数据异常") ;
//		}
////		Car car = carService.getById(biz.getCarId());
////		if(car == null) {
////			return getErrorMessage("数据异常") ;
////		}
//		String sign = orderId + order.getCompanyId() + order.getPrice() + order.getKeeperMoney() + key;
//		String signMd5 = MD5Utils.getMD5Str(sign);
//		//签名的话 orderId + companyId + price + keeperMoney + key
//		if(!signMd5.equals(signature)) {
//			return getErrorMessage("签名不合法") ;
//		}
//
//		BigDecimal profit = FunctionUtils.sub(order.getPrice(), order.getKeeperMoney(), 2) ; //这里是承运商实际收入的金额
//		String str = doHandleDetail(car.getCid(), HandleTypeEnum.order.getId(), Constant.moneyIn, profit, "订单完成收入");
//		if(StrUtil.isNotEmpty(str)) {
//			throw new BusinessException(str) ;
//		}

		return new ObjectRestResponse<>().succeed("操作成功") ;
	}
	
	private BaseResponse getErrorMessage(String message) {
		return new ObjectRestResponse<>().error(message); 
	}

	@Transactional
	@Override
	public String doHandleDetail(String cid,Integer typeid, Integer isout, BigDecimal money,String remark) {
		String result = "" ;
		String paycode = FunctionUtils.getOrderCode(1, 2) ;
		try {
			CysAccount account = getByCid(cid);
			BigDecimal original = account.getMoney() ; //原始金额
			BigDecimal bond = account.getMoney() ; 
			String str = "" ;
			if(Constant.moneyIn == isout) {
				//收入
				bond = FunctionUtils.add(bond, money, 2) ;
				str = "【收入】：" ;
			}else {
				//支出
				bond = FunctionUtils.sub(bond, money, 2) ;
				str = "【支出】：" ;
			}
			if(bond.compareTo(BigDecimal.ZERO) < 0) {
				return "本次余额使用超过原始余额" ;
			}
			account.setMoney(bond); 
			boolean flag = super.updateById(account);
			if(!flag) {
				return "操作失败" ;
			}
			CysAccountDetail cysAccountDetail = new CysAccountDetail();
			cysAccountDetail.setCid(cid); 
			cysAccountDetail.setPaycode(paycode);
			cysAccountDetail.setTypeid(typeid);
			cysAccountDetail.setRemark(str+remark);
			cysAccountDetail.setIsout(isout);
			cysAccountDetail.setOriginal(original);
			cysAccountDetail.setCost(money);
			cysAccountDetail.setLast(bond);
			cysAccountDetail.setCreatetime(new Date());
			
			cysAccountDetailService.save(cysAccountDetail) ;
		}catch(Exception e) {
			logger.info("保存效验余额异常：" + e.getMessage());;
			throw new BusinessException("保存效验余额异常") ;
		}
		
		return result;
	}
	
	
}
